import os
import requests
import configparser
from tqdm import tqdm

#随机美女视频下载

def get_max_file_number(default_video_path):
    if not os.path.exists(default_video_path):
        os.makedirs(default_video_path)
    max_num = 0
    for filename in os.listdir(default_video_path):
        if filename.endswith('.mp4'):
            try:
                num = int(os.path.splitext(filename)[0])
                if num > max_num:
                    max_num = num
            except ValueError:
                continue
    return max_num


def get_video_count_url(default_video_path):
    video = input("请输入视频下载链接\n")
    count = input("输入下载视频的数量\n")
    download_video(video, int(count), default_video_path)


def download_video(video, count, default_video_path):
    start_num = get_max_file_number(default_video_path) + 1
    try:
        for i in range(count):
            file_num = start_num + i
            file_path = os.path.join(default_video_path, f'{file_num}.mp4')
            response = requests.get(video, stream=True)
            total_size_in_bytes = int(response.headers.get('content-length', 0))
            block_size = 1024
            # 设置进度条颜色为白色
            progress_bar = tqdm(total=total_size_in_bytes, unit='iB', unit_scale=True, colour='white')
            with open(file_path, 'wb') as file:
                for data in response.iter_content(block_size):
                    progress_bar.update(len(data))
                    file.write(data)
            progress_bar.close()
            if total_size_in_bytes != 0 and progress_bar.n != total_size_in_bytes:
                print("下载过程中出现问题")
    except requests.RequestException as e:
        print(f"请求出错: {e}")


if __name__ == '__main__':
    config = configparser.ConfigParser()
    config.read('config.ini')
    try:
        default_video_path = config.get('Paths', 'default_video_path')
    except (configparser.NoSectionError, configparser.NoOptionError):
        print("在 config.ini 文件中未找到 default_video_path 配置，请检查文件。")
    else:
        get_video_count_url(default_video_path)
